import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

/**
 * 本管道用于格式化字符串
 * 支持管道串联
 */
@Pipe({
    name: 'format'
})
export class FormatPipe implements PipeTransform {

    /**
    * 格式化函数单元集合
    */
    private formattersUnits = {
        parseBool: x => parseInt(x, 10) === 1,
        yesOrNo: x => x ? '是' : '否',
        dollar: x => x + ' USD',
        rmb: x => x + ' CNY',
        decimal2: x => {
            let res = parseFloat(x);
            if (isNaN(res)) { return x; }
            res = Math.round(x * 100) / 100;
            return res;
        },
        hundred: x => parseFloat('' + x) * 100,
        toPercent: x => x + '%',
        parseFloat: x => parseFloat('' + x),
        parseInt: x => parseInt('' + x, 10)
    };

    transform(value: any, formatter?: any): any {
        if (value === undefined) return '';
        if (value === null) return '';
        if (formatter) {
            if (typeof formatter === 'string') {
                const item = formatter.split('.');
                if (item.length) {
                    item.forEach(key => {
                        if (key && key.length && this.formattersUnits.hasOwnProperty(key)) {
                            const fn = this.formattersUnits[key];
                            value = fn(value);
                        }
                    });
                }
            } else if (typeof formatter === 'function') {
                return formatter(value);
            }
        }
        return value;
    }

}
